package order

import (
	"strconv"
	"time"
	"encoding/json"

	"shop_be/dao"
	"shop_be/model"
	"shop_be/util"
)

func createOrder(uid string, prd, address string) model.Msg {

	msg := model.Msg{}
	msg.Code = 0
	msg.Msg = "ok"

	product := []model.Product{}
	json.Unmarshal([]byte(prd), &product)

	uid1, _ := strconv.Atoi(uid)

	for i := range product {
		b := dao.FindProductByIdDao(product[i].Id)
		if b.TotalCount < product[i].Count {
			msg.Code = 1
			msg.Msg = "库存不足"
			return msg
		}
	}

	for i := range product {
		b := dao.FindProductByIdDao(product[i].Id)
		b.TotalCount -= product[i].Count

		order := model.Order{}
		order.Time = time.Now()
		order.Uid = uid1
		order.Pid = b.Id
		order.Count = product[i].Count
		order.TotalPrice = product[i].Price * float32(product[i].Count)
		order.Time = time.Now().AddDate(0, 1, 0)
		order.PrdName = product[i].Name
		order.URL = product[i].Url
		order.Address = address
		dao.CreateOrder(order)
		dao.UpdateProductDao(b)
	}

	return msg

}

func findOrder(uid string) []model.Order {
	msg := model.Msg{}
	msg.Code = 0
	msg.Msg = "ok"

	uid1, _ := strconv.Atoi(uid)
	bSlice := dao.FindOrder(uid1)
	return bSlice

}

func createShopcart(s string, uid string) model.Msg {
	msg := model.Msg{}
	msg.Code = 0
	msg.Msg = "ok"

	uid1, _ := strconv.Atoi(uid)

	//uid2:=int()
	b := model.Product{}
	json.Unmarshal([]byte(s), &b)
	sc := model.Shopcart{}

	sc.Uid = uid1
	sc.Pid = b.Id
	sc.Count = b.Count
	sc.Time = time.Now()

	dao.CreateShopcart(sc)
	return msg
}

func findShopcart(uid string) model.Msg {
	msg := model.Msg{}
	msg.Code = 0
	msg.Msg = "ok"

	uid1, _ := strconv.Atoi(uid)

	sc := dao.FindShopCart(uid1)
	msg.Data = sc
	return msg

}

func getAllOrder() []model.Order {
	order := []model.Order{}
	util.Db.Find(&order)
	return order
}
